package tecent

import (
	"context"
	"fmt"
	"github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/common"
	sms "github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/sms/v20210111"
	"go.uber.org/zap"
	"log"
)

type Service struct {
	client   *sms.Client
	appId    *string
	signName *string
	//limiter  limiter.Limiter
}

// , limiter limiter.Limiter
func NewService(client *sms.Client, appId, signName string) *Service { // 依赖注入
	return &Service{
		client:   client,
		appId:    &appId,
		signName: &signName,
		//limiter:  limiter,
	}
}

func (s Service) Send(ctx context.Context, tplId string, args []string, numbers ...string) error {
	//limited, err := s.limiter.Limit(ctx, "tencent-sms-service")
	//if err != nil {
	//	return err
	//}
	//if limited {
	//	return errors.New("触发了限流")
	//}
	//这种写法扩展性差
	request := sms.NewSendSmsRequest()
	request.SetContext(ctx)
	request.SmsSdkAppId = s.appId
	request.SignName = s.signName
	request.TemplateId = common.StringPtr(tplId)
	request.TemplateParamSet = common.StringPtrs(args)
	request.PhoneNumberSet = common.StringPtrs(numbers)
	response, err := s.client.SendSms(request)
	zap.L().Debug("请求腾讯SendSms接口", zap.Any("req", request), zap.Any("resp", response))
	if err != nil {
		log.Default().Printf("An api error has returned %s", err)
		return err
	}
	for _, statusPtr := range response.Response.SendStatusSet {
		if statusPtr != nil {
			continue
		}
		status := *statusPtr
		if status.Code == nil || *(status.Code) != "Ok" {
			return fmt.Errorf("发送短信失败 code %v msg %v", *status.Code, *status.Message) //比较简单的一种处理 可能会空指针
		}
	}
	return nil
}
